import React, { useEffect, useState } from 'react';
import { Table, Button, message, Space, Popconfirm, Drawer, Select } from 'antd';
import { PlusOutlined, SettingOutlined } from '@ant-design/icons';
import { contentService } from '@/services/contentService';
import { Article, Column } from '@/types/content';
import ColumnManager from './components/ColumnManager';
import ArticleEditor from './components/ArticleEditor';

const { Option } = Select;

const ArticleList: React.FC = () => {
  const [articles, setArticles] = useState<Article[]>([]);
  const [columns, setColumns] = useState<Column[]>([]);
  const [loading, setLoading] = useState(false);
  const [articleModalVisible, setArticleModalVisible] = useState(false);
  const [columnDrawerVisible, setColumnDrawerVisible] = useState(false);
  const [editingArticle, setEditingArticle] = useState<Article | null>(null);
  const [selectedColumnId, setSelectedColumnId] = useState<number | null>(null);

  // 获取文章和栏目
  const fetchData = async () => {
    setLoading(true);
    try {
      const [artRes, colRes] = await Promise.all([
        contentService.getArticles(),
        contentService.getColumns()
      ]);
      setArticles(artRes.data.data?.results || []);
      setColumns(colRes.data.data?.results || []);
    } catch {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  // 文章相关操作
  const handleAddArticle = () => {
    setEditingArticle(null);
    setArticleModalVisible(true);
  };

  const handleEditArticle = (art: Article) => {
    setEditingArticle(art);
    setArticleModalVisible(true);
  };

  const handleDeleteArticle = async (id: number) => {
    try {
      await contentService.deleteArticle(id);
      message.success('删除成功');
      fetchData();
    } catch {
      message.error('删除失败');
    }
  };

  const handleArticleSuccess = () => {
    setArticleModalVisible(false);
    fetchData();
  };

  const handleColumnsChange = (newColumns: Column[]) => {
    setColumns(newColumns);
  };

  // 筛选后的文章
  const filteredArticles = selectedColumnId 
    ? articles.filter(art => art.column.id === selectedColumnId)
    : articles;

  const tableColumns = [
    { title: 'ID', dataIndex: 'id', width: 60 },
    { title: '标题', dataIndex: 'title' },
    { title: '摘要', dataIndex: 'summary' },
    {
      title: '栏目',
      dataIndex: ['column', 'name'],
      render: (_: any, record: Article) => record.column?.name || '-',
    },
    {
      title: '作者',
      dataIndex: 'author',
      width: 100,
    },
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover: string) => cover ? <img src={cover} alt="cover" style={{ width: 60, height: 40, objectFit: 'cover' }} /> : '-',
      width: 80,
    },
    {
      title: '发布时间',
      dataIndex: 'created_at',
      render: (t: string) => t ? t.replace('T', ' ').slice(0, 19) : '-',
      width: 160,
    },
    {
      title: '状态',
      dataIndex: 'is_published',
      render: (v: boolean) => v ? '已发布' : '未发布',
      width: 80,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_: any, record: Article) => (
        <Space>
          <Button type="link" onClick={() => handleEditArticle(record)}>编辑</Button>
          <Popconfirm title="确定删除该文章吗？" onConfirm={() => handleDeleteArticle(record.id)}>
            <Button type="link" danger>删除</Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      {/* 顶部操作栏 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAddArticle}>添加文章</Button>
          <Button icon={<SettingOutlined />} onClick={() => setColumnDrawerVisible(true)}>管理栏目</Button>
        </Space>
        <Select
          placeholder="选择栏目筛选"
          allowClear
          style={{ width: 200 }}
          value={selectedColumnId}
          onChange={setSelectedColumnId}
        >
          {columns.map(col => <Option value={col.id} key={col.id}>{col.name}</Option>)}
        </Select>
      </div>

      {/* 文章列表 */}
      <Table
        rowKey="id"
        columns={tableColumns}
        dataSource={filteredArticles}
        loading={loading}
        bordered
      />

      {/* 文章编辑组件 */}
      <ArticleEditor
        visible={articleModalVisible}
        editingArticle={editingArticle}
        columns={columns}
        onCancel={() => setArticleModalVisible(false)}
        onSuccess={handleArticleSuccess}
      />

      {/* 栏目管理抽屉 */}
      <Drawer
        title="栏目管理"
        open={columnDrawerVisible}
        onClose={() => setColumnDrawerVisible(false)}
        width={400}
      >
        <ColumnManager
          columns={columns}
          onColumnsChange={handleColumnsChange}
          onRefresh={fetchData}
        />
      </Drawer>
    </div>
  );
};

export default ArticleList; 